package com.wlj.web.controller;

import com.wlj.result.CodeMsg;
import com.wlj.vo.JsonRes;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.wlj.exception.CustomException;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonRes<String> exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();
        if(e instanceof CustomException) {
            CustomException ex = (CustomException)e;
            return JsonRes.error(ex.getMessage());
        }else if(e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
            BindingResult bindingResult = ex.getBindingResult();
            if(bindingResult.hasErrors()){
                StringBuilder errMsg = new StringBuilder();
                bindingResult.getAllErrors().stream().forEach(error-> {
                    errMsg.append(error.getDefaultMessage()+" ");
                });
                CodeMsg errorMsg = CodeMsg.BIND_ERROR.fillArgs(errMsg.toString());
                return JsonRes.error(errorMsg.getMsg());
            }
        }
        return JsonRes.error();
    }
}
